// Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.
// This source file is part of the Cangjie project, licensed under Apache-2.0
// with Runtime Library Exception.
//
// See https://cangjie-lang.cn/pages/LICENSE for license information.

#include <iostream>
#include <sstream>
#include <fstream>
#include <regex>

#include "Deveco/Log.h"

using namespace CangjieMigrator;
using namespace CangjieMigrator::Deveco;

Log::Log(std::vector<std::string> content) : content(std::move(content))
{}

std::string Log::ToString() const
{
    auto result = std::ostringstream();
    auto c = content.begin();
    result << *c;
    for (; c != content.end(); ++c) {
        result << *c << std::endl;
    }
    return result.str();
}

static constexpr int LOG_HEAD_LENGTH = sizeof("[0000-00-00T00:00:00.000] [DEBUG] debug-file - ") - 1;

static bool HasLogHead(const std::string &line)
{
    static auto pattern = std::regex(R"(^\[\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}\] \[DEBUG\] debug-file - )");
    return std::regex_search(line, pattern);
}

std::vector<Log> Log::ReadLogsAndSelectDebug(const Path &logFile)
{
    auto file = std::ifstream(logFile);
    if (!file) {
        std::cerr << "Open read file " << logFile << " failed." << std::endl;
        return {};
    }

    auto result = std::vector<Log>();
    std::vector<std::string> current;
    std::string line;
    while (std::getline(file, line)) {
        if (line.empty()) {
            continue;
        }
        if (HasLogHead(line)) {
            if (!current.empty()) {
                result.emplace_back(Log(std::move(current)));
            }
            current.emplace_back(line.substr(LOG_HEAD_LENGTH));
        } else {
            current.emplace_back(line);
        }
    }
    return result;
}
